define(['jquery', 'underscore', 'backbone', 'bootstrap', 'text!templates/BaseModuleTemplate.jst'], 
		function($, _, Backbone, bt, BaseModuleTemplate) {
 var BaseModule={};
 var PaginatedCollection=BaseModule.PaginatedCollection = Backbone.Collection.extend({
  initialize: function(param) {
	  this.baseUrl=param.baseUrl;
	  this.perPage=param.perPage;
    _.bindAll(this, 'parse', 'url', 'pageInfo', 'nextPage', 'previousPage');
    typeof(options) != 'undefined' || (options = {});
    this.page = 1;
    typeof(this.perPage) != 'undefined' || (this.perPage = 10);
    
	this.bind("exception",function(errMes){
			console.log("encountered exception when retrieve data from server!"+errMes);
	}) ;
  },
  fetch: function(options) {
    typeof(options) != 'undefined' || (options = {});
    Backbone.Events.trigger("showStatus","loading......",false);
    var self = this;
    var success = options.success;
    options.success = function(resp) {
    	//console.log("fetched");
      Backbone.Events.trigger("showStatus","Load successful!",true);
      if(success) { success(self, resp); }
    };
    //console.log("fetch");
    return Backbone.Collection.prototype.fetch.call(this, options);
  },
  parse: function(res) {
	  if(res.success){
		  this.page = res.success.pagingInfo.page;
		  this.perPage = res.success.pagingInfo.perPage;
		  this.total = res.success.pagingInfo.total;
		  return res.success.models;
	}else if(res.failed && res.failed.errorType){
		Backbone.Events.trigger("requestFailed",res.failed);
		this.trigger("exception",res.failed,this);
	 }else{
		 this.trigger("exception","Unexpected data!",this);
	 }
  },
  url: function(queryData) {
	  if(queryData === undefined){
		  
	  }else{
		  if(queryData != null){
			  this.queryData=queryData;
		  }
	  }
	  if(this.queryData === undefined){
		  return this.baseUrl + '?' + $.param({page: this.page, perPage: this.perPage});
	  }else{
		  return this.baseUrl + '?' + $.param({page: this.page, perPage: this.perPage})+'&'+$.param(this.queryData);
	  }
     
  },
  pageInfo: function() {
    var info = {
      total: this.total,
      page: this.page,
      perPage: this.perPage,
      pages: Math.ceil(this.total / this.perPage),
      prev: false,
      next: false
    };
 
    var max = Math.min(this.total, this.page * this.perPage);
 
    if (this.total == this.pages * this.perPage) {
      max = this.total;
    }
 
    info.range = [(this.page - 1) * this.perPage + 1, max];
    info.pageNums=new Array(info.pages);
    var startNum=info.pages/2-2;
    if(startNum<0){
    	startNum=0;
    }
    var endNum=info.pages/2+3;
    if(endNum>info.pages){
    	endNum=info.pages;
    }
    for(var i=0;i<(endNum-startNum);i++){
    	info.pageNums[i]=startNum+i+1;
    }
    if (this.page > 1) {
      info.prev = this.page - 1;
    }
 
    if (this.page < info.pages) {
      info.next = this.page + 1;
    }
 
    return info;
  },
  nextPage: function() {
    if (!this.pageInfo().next) {
      return false;
    }
    this.page = this.page + 1;
    return this.fetch();
  },
  previousPage: function() {
    if (!this.pageInfo().prev) {
      return false;
    }
    this.page = this.page - 1;
    return this.fetch();
  },
  toPage:function(pageNum){
	  if(pageNum<0 || pageNum>this.pageInfo().pages){
		  return false;
	  }
	  this.page=pageNum;
	  return this.fetch();
  }
 
});


 var PaginatedView =BaseModule.PaginatedView= Backbone.View.extend({
	  tagName:"div",
	  template:_.template(BaseModuleTemplate),
	  className:"pagination",
	  initialize: function() {
	    _.bindAll(this, 'previous', 'next', 'render');
	    this.collection.bind('refresh', this.render);
	  },
	  events: {
	    'click a.prev': 'previous',
	    'click a.toPage': 'gotoPage',
	    'click a.next': 'next'
	  },
	  render: function() {
		  if(this.collection.length >0){
			  $(this.el).html(this.template({'tempId':'paging','data':this.collection.pageInfo()}));
		  }
	    return this;
	  },
	 
	  previous: function(e) {
		  e.preventDefault();
	    this.collection.previousPage();
	    return false;
	  },
	 
	  next: function(e) {
		  e.preventDefault();
	    this.collection.nextPage();
	    return false;
	  },
	  gotoPage:function(e){
		  e.preventDefault();
		  var pageNum=$(e.target || e.srcElement).attr("href");
		  this.collection.toPage(pageNum);
		    return false;
	  }
	});
 
 var BaseModel=BaseModule.BaseModel=Backbone.Model.extend({
	 parse:function(res){
		 if(res.success){
			 return res.success;
		 }else if(res.failed && res.failed.errorType){
			 Backbone.Events.trigger("requestFailed",res.failed);
			 this.trigger("exception",res.failed,this);
		 }else{
			 return res;
		 }
	 }
 });
 
 var BaseCollection=BaseModule.BaseCollection=Backbone.Collection.extend({
	 initialize:function(){
		this.bind("failed",function(errMes){
			console.log("encountered exception when retrieve data from server!"+errMes);
		}) ;
	 },
	 parse:function(res){
		 if(res.success){
			 return res.success;
		 }else if(res.failed && res.failed.errorType){
			 Backbone.Events.trigger("requestFailed",res.failed);
			 this.trigger('failed',res.failed);
			 
		 }else{
			 this.trigger("exception","Unexpected data!",this);
		 }
	 }
 });
 
 //==============Global resource
 var WebRoot=BaseModule.WebRoot="";
 
 
 //===============No Result view ===========
 var NoResult=BaseModule.NoResult=Backbone.View.extend({
	 tagName:"div",
	 className:"hero-unit",
	 template:_.template(BaseModuleTemplate),
	 events:{
		'click #noResultFresh':"fresh"
	 },
	 initialize:function(mes,pview){
		 this.message=mes;
		 this.parentView=pview;
		 this.render();
	 },
	 render:function(){
		$(this.el).html(this.template({'tempId':'NoReult','data':{
			"message":this.message
		}})); 
		$(this.parentView.el).html(this.el);
		return this;
	 },
	 fresh:function(e){
		 e.preventDefault();
		 this.parentView.render(); 
	 }
 });
 
 var BaseRouter=BaseModule.BaseRouter=Backbone.Router.extend({
	
 	routes:{
 		"IndexModule":"indexModule",
 		"IdearModule":"idearModule",
 		"BlogModule":"blogModule"
 	},
 	idearModule:function(){
 		$('#topNavUL>li').removeClass("active");
 		$('#topNavUL>li:eq(1)').addClass("active")
 		Backbone.Events.trigger("shiftModule","idear");
 	},
 	blogModule:function(){
 		$('#topNavUL>li').removeClass("active");
 		$('#topNavUL>li:eq(2)').addClass("active")
 		Backbone.Events.trigger("shiftModule","blog");
 	},
 	indexModule:function(){
 		$('#topNavUL>li').removeClass("active");
 		$('#topNavUL>li:eq(0)').addClass("active")
 		Backbone.Events.trigger("shiftModule","index");
 	}
 	
 	
 });
 
 return BaseModule;
});
